import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  message,
  Card,
} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { AdminControllerService } from "../api";
import type { VidVideoCompilation_ } from "../api";

interface CollectionData {
  id?: string;
  name?: string;
  sortNum?: string;
  createdTime?: string;
  updatedTime?: string;
}

const CollectionManagement: React.FC = () => {
  const [collections, setCollections] = useState<CollectionData[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCollection, setEditingCollection] =
    useState<CollectionData | null>(null);
  const [loading, setLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);

  const [form] = Form.useForm();

  // 加载合集列表
  const loadCollections = async () => {
    setTableLoading(true);
    try {
      const response = await AdminControllerService.compilationListUsingPost();
      if (response.data) {
        setCollections(response.data.records || []);
      }
    } catch (error: any) {
      console.error("加载合集列表失败:", error);
      message.error(error.response?.data?.message || "加载合集列表失败");
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    loadCollections();
  }, []);

  const columns: ColumnsType<CollectionData> = [
    {
      title: "合集名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "排序",
      dataIndex: "sortNum",
      key: "sortNum",
      sorter: (a, b) => Number(a.sortNum || 0) - Number(b.sortNum || 0),
    },
    {
      title: "创建时间",
      dataIndex: "createdTime",
      key: "createdTime",
      render: (time: string) => (time ? new Date(time).toLocaleString() : "-"),
    },
    {
      title: "更新时间",
      dataIndex: "updatedTime",
      key: "updatedTime",
      render: (time: string) => (time ? new Date(time).toLocaleString() : "-"),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个合集吗？"
            description="删除合集后，该合集下的所有视频将被移除合集关联"
            onConfirm={() => record.id && handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingCollection(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (collection: CollectionData) => {
    setEditingCollection(collection);
    form.setFieldsValue({
      name: collection.name,
      sortNum: collection.sortNum,
    });
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    if (!id) {
      message.error("合集ID不能为空");
      return;
    }
    try {
      const data = await AdminControllerService.deleteCompilationUsingPost(id);
      if (data.code !== 20000) {
        message.error(data.message || "删除失败");
        return;
      }
      message.success("删除成功");
      loadCollections();
    } catch (error: any) {
      console.error("删除合集失败:", error);
      message.error(error.response?.data?.message || "删除失败");
    }
  };

  const handleModalOk = () => {
    form.validateFields().then(async (values) => {
      setLoading(true);
      try {
        const compilationData: VidVideoCompilation_ = {
          ...values,
          sortNum: values.sortNum?.toString(),
        };

        if (editingCollection?.id) {
          // 编辑
          compilationData.id = editingCollection.id;
        }

        await AdminControllerService.saveCompilationUsingPost(compilationData);
        message.success(editingCollection ? "修改成功" : "添加成功");
        setIsModalVisible(false);
        loadCollections();
      } catch (error: any) {
        console.error("保存合集失败:", error);
        message.error(error.response?.data?.message || "保存失败");
      } finally {
        setLoading(false);
      }
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <Card
      title="合集管理"
      extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加合集
        </Button>
      }
    >
      <Table
        columns={columns}
        dataSource={collections}
        rowKey="id"
        loading={tableLoading}
        pagination={false}
      />

      <Modal
        title={editingCollection ? "编辑合集" : "添加合集"}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={500}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            sortNum: "1",
          }}
        >
          <Form.Item
            name="name"
            label="合集名称"
            rules={[{ required: true, message: "请输入合集名称" }]}
          >
            <Input placeholder="请输入合集名称" />
          </Form.Item>

          <Form.Item
            name="sortNum"
            label="排序"
            rules={[{ required: true, message: "请输入排序号" }]}
          >
            <Input type="number" placeholder="请输入排序号" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default CollectionManagement;
